<?php
namespace Particle\Core;
use Particle\Core as Core;
use Particle\Apps as Apps;

require_once CORE_PATH . 'libs' . DS . 'smarty' . DS . 'Smarty.class.php';

/**
 * 
 * @package Particle
 * @category Core
 * @author dertin
 *
 **/
final class View extends \Smarty
{
    private static $controller;
    private static $method;
    private static $cacheKey;

    private static $css;
    private static $js;
    private static $jsHead;
    
    
    public function __construct($controller, $method, $cacheKey = false) {
        
        parent::__construct();
        
        $cacheDir = CORE_PATH . 'tmp' . DS . 'cache-smarty'. DS;
        $compileDir = CORE_PATH . 'tmp' . DS .'template-compiler-smarty' . DS;
        $configDir = Apps\Settings::getInstance()->getSettingsConfDirSmarty();
        
        if(isset($compileDir) && is_dir($compileDir)){
            $this->setCompileDir ( $compileDir );
        }else{
            // TODO: ERROR
        }
        
        if(isset($configDir) && is_dir($configDir)){
            
            $aFilesSettingsSmarty = Apps\Settings::getInstance()->getSettingsFilesmarty();

            $this->setConfigDir ( $configDir );

            $countFilesSettingsSmarty = count($aFilesSettingsSmarty);

            for($in = 0; $in < $countFilesSettingsSmarty; $in++){

                if(is_file($aFilesSettingsSmarty[$in])){
                    $this->configLoad($aFilesSettingsSmarty[$in]);
                }
                
            }
        }
        
        if(CACHE){
            $this->caching = true;
            
            $this->setCacheDir ( $cacheDir );
            
            if(DEBUG_MODE){
                $this->debugging = true;
            }else{
                $this->debugging = false;
            }

            if(TIME_CACHE){
                $this->clearAllCache(TIME_CACHE);
            }
            
            if(LIMIT_MB_CACHE){
                if($this->foldersize($cacheDir) >= LIMIT_MB_CACHE){
                    $this->clearAllCache();
                }
            }
        } else {
            
            $this->caching = false;
        
        }
        
        self::$controller = $controller;
        self::$method = $method;
        self::$cacheKey = $cacheKey;
        //self::$css = array();
        //self::$js = array();
        //self::$jsHead = array();
        
    }
    
    public function show($view = false, $customController=false, $return=false)
    {   
        if(!$view){
            $view = self::$method;
        }
        
        if(is_string($customController)){
            $viewController = $customController;
        }else{
            $viewController = self::$controller;
        }
        
        $aCSS = array();
        $aJS = array();
        $aJSHead = array();
        
        if(count(self::$css)){
            $aCSS = self::$css;
        }
        
        if(count(self::$js)){
            $aJS = self::$js;
        }
        
        $aFilesSettingsJS = Apps\Settings::getInstance()->getSettingsFilejs();
        
        if(isset($aFilesSettingsJS) && is_array($aFilesSettingsJS)){
            
            $countFilesJS = count($aFilesSettingsJS);
            for($f=0; $f < $countFilesJS; $f++){
                $aJS[] = $aFilesSettingsJS[$f];
            }
            
        }
        
        if(count(self::$jsHead)){
            $aJSHead = self::$jsHead;
        }
        

        $absoluteView = APP_PATH . 'views' . DS . $viewController;
        $pathView = $absoluteView . DS . $view . '.tpl';
        
        
        $_params = array (
            'path_layout' => BASE_URL_APPS . 'views/layout/' . DEFAULT_LAYOUT,
            'css' => $aCSS,
            'js' => $aJS,
            'jsHead' => $aJSHead,
            'home' => HOME_URL,
            'public' => BASE_URL_APPS . 'public/',
            'controller' => $viewController,
            'tplname' => $view,
            'path_view' => BASE_URL_APPS . 'views/' . $viewController,
            'absolute_view' => $absoluteView
        ); //absolute_view TODO: no sera pathView ?
        
        if(is_readable($pathView)){
           
           $this->setTemplateDir ( APP_PATH . 'views' . DS . 'layout'. DS . DEFAULT_LAYOUT . DS ); 
           $this->addTemplateDir( $absoluteView, 'currentview' );
           
           if(!$this->isCached('header.tpl', self::$cacheKey) || !$this->isCached('footer.tpl', self::$cacheKey)) {             
                $this->assign('_layoutParams', $_params); 
           }
           
           $sHeader = $this->fetch( 'header.tpl', self::$cacheKey );
           $sFooter = $this->fetch( 'footer.tpl', self::$cacheKey );
           
           $sView = $this->fetch( $pathView, self::$cacheKey );
           
           if($return == false){
                if(OUTPUT_CONTROL){
                     // Get Unexpected output internal //
                     $unexpected_output_internal = ob_get_contents();

                     ob_clean();

                     // Check Unexpected output //
                     if($unexpected_output_internal){
                          Core\Debug::savelogfile(2, 'Unexpected output internal', $unexpected_output_internal);
                          throw new \Exception('Unexpected output internal');
                     }
                }

                    echo $sHeader;
                    echo $sView;
                    echo $sFooter;
                    
           }else{
               
               switch ($return) {
                    case 'full':
                        return $sHeader.$sView.$sFooter;
                    break;
                    case 'onlyview':
                        return $sView;
                    default:
                        return $sHeader.$sView.$sFooter;
                    break;
               }
              
               
           }
        }
        else {
            throw new \Exception('Error PATH View');
        }
        
    }
    
    
    public function setJs(array $js, $head = false, $customController=false, $checkUrl=false)
    {
        
        if(is_string($customController)){
            $viewController = $customController;
        }else{
            $viewController = self::$controller;
        }
        
        if(is_array($js) && count($js)){
            for($i=0; $i < count($js); $i++){
                
                $jsFile = BASE_URL_APPS . 'views/' . $viewController . '/js/' . $js[$i] . '.js';

                if($checkUrl && !is_readable($jsFile)){
                   throw new \Exception('Error PATH setJS');
                }
                
                if($head){
                   self::$jsHead[] = $jsFile;

                }else{
                   self::$js[] = $jsFile;
                }

            }
        } else {
            throw new \Exception('Error JS');
        }
    }
    
    
    public function setCss(array $css, $customController=false, $checkUrl=false)
    {
        if(is_string($customController)){
            $viewController = $customController;
        }else{
            $viewController = self::$controller;
        }

		
        if(is_array($css) && count($css)){
            for($i=0; $i < count($css); $i++){
                
                $cssFile = BASE_URL_APPS . 'views/' . $viewController . '/css/' . $css[$i] . '.css';
                
                if($checkUrl && !is_readable($cssFile)){
                   throw new \Exception('Error PATH setCss');
                }
                
                self::$css[] = $cssFile;
                
                
                
            }
        } else {
            throw new \Exception('Error CSS');
        }
    }
    
    
    private function foldersize($file) {
    
        $size = 0;
        
        if (is_dir($file)) {
            
            $rdir = opendir($file);

            while ($cfile = readdir($rdir)){
                
                if ($cfile != '.' && $cfile != '..'){
                    
                    $size += filesize($file . '/' . $cfile);                    
                }
            }
        }
        else{
            return 0;
        }
              
        $kbytes = (float) $size / 1024;
        $mbytes = (float) $kbytes / 1024;
        
        return round ($mbytes,2);
    
    }
    
}